package com.cx.webflux.handler;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Date;

/**
 * 时间处理handler
 *
 * @author 旭旭
 * @create 2018-07-30 22:42
 **/
@Component
public class TimeHandler {

    public Mono<ServerResponse> getTime(ServerRequest request){
        return ServerResponse.ok().contentType(MediaType.TEXT_PLAIN).body(
                Mono.just("Now is " + new SimpleDateFormat("HH:mm:ss").format(new Date())),String.class
        );
    }

    public Mono<ServerResponse> getDate(ServerRequest request){
        return ServerResponse.ok().contentType(MediaType.TEXT_PLAIN).body(
                Mono.just("Today is " + new SimpleDateFormat("yyyy-MM-dd ").format(new Date())),String.class
        );
    }

    public Mono<ServerResponse> sendTimePerSec(ServerRequest serverRequest) {
        return ServerResponse.ok().contentType(MediaType.TEXT_EVENT_STREAM).body(  // text/event-stream ，即SSE；
                Flux.interval(Duration.ofSeconds(1)).   // 利用interval生成每秒一个数据的流
                        map(l -> new SimpleDateFormat("HH:mm:ss").format(new Date())),
                String.class);
    }
}
